package cn.stylefeng.guns.modular.yingbao.handler;

import cn.stylefeng.guns.modular.yingbao.entity.*;
import cn.stylefeng.guns.modular.yingbao.service.*;
import cn.stylefeng.guns.rabbitmq.producer.Sender;
import cn.stylefeng.guns.rabbitmq.vo.MessageVo;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.Date;

/**
 * @author jj
 * @date 2019/12/18 15:41
 */
@Slf4j
@Service
public class BuildingHandler {

    @Autowired
    Sender sender;

    @Lazy
    @Autowired
    SysBuildingService sysBuildingService;
    @Autowired
    SysUserService sysUserService;

    @Autowired
    UserMoneyService userMoneyService;

    @Autowired
    UserMoneySettingService userMoneySettingService;

    @Autowired
    UserMoneyLogService userMoneyLogService;

    @Autowired
    SysRebateSettingService sysRebateSettingService;

    @Autowired
    SysRebateService sysRebateService;

    @Autowired
    SysUserGroupService sysUserGroupService;

    @Autowired
    SysGroupSettingService sysGroupSettingService;

    @Autowired
    ContractSettingService contractSettingService;

    @Lazy
    @Autowired
    GroupHandler groupHandler;


    public void building(SysBuilding sysBuilding ) {
        if (sysBuilding==null){
            log.error("建仓错误！" );
        }
        Integer fate = sysBuilding.getFate()*1000*60*60;
        MessageVo msg = new MessageVo();
        msg.setType("建仓" );
        msg.setTimestamp(fate.toString());
        msg.setMessage(sysBuilding.getOrdinal());
        msg.setId(sysBuilding.getUserid());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sender.sendJCMsg(msg,sysBuilding.getType(),sysBuilding.getIsVip());
    }
    @Transactional(rollbackFor = Exception.class)
    public  void buildingHandler(JSONObject data) {
        SysBuilding sysBuilding;
        String buildId = data.getString("message");
        Long id = data.getLong("id");
        sysBuilding= sysBuildingService.getOne(new QueryWrapper<SysBuilding>().eq("ordinal",buildId));

        if (sysBuilding==null){
            sysBuilding = sysBuildingService.getOne(new QueryWrapper<SysBuilding>().eq("userid",id).eq("stuats","1"));
        }else {
            String stuats = sysBuilding.getStuats();
            if ("2".equals(stuats)){
                log.error("建仓已完成",sysBuilding);
                return;
            }
        }

       /* sysBuilding.setStuats("2");
        sysBuilding.setMoney(sysBuilding.getPrice()*sysBuilding.getEarnings()/100);
        sysBuilding.setBuildingTime(new Date());
        int version5 = sysBuilding.getVersion();
        sysBuildingService.update(sysBuilding,new QueryWrapper<SysBuilding>().eq("id",sysBuilding.getId()).eq("version",version5));
*/
        Long userid = sysBuilding.getUserid();
        UserMoney userMoney = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("userid", userid));
        userMoney.setAvailMoney(userMoney.getAvailMoney()+sysBuilding.getPrice()+(sysBuilding.getPrice()*sysBuilding.getEarnings()/100));
        if (userMoney.getFrozenCapital()==0){
            UserMoneySetting userMoneySetting = userMoneySettingService.getOne(null);
            userMoney.setFrozenCapital(userMoneySetting.getFrozenCapital());
            userMoney.setAvailMoney(userMoney.getAvailMoney()-userMoney.getFrozenCapital());
            userMoney.setBackup1(userMoneySetting.getFrozenDay());
            UserMoneyLog userMoneyLog=new UserMoneyLog();
            userMoneyLog.setUserid(userid);
            userMoneyLog.setRemark("冻结");
            userMoneyLog.setCreateTime(new Date());
            userMoneyLog.setMoney(userMoney.getFrozenCapital());
            userMoneyLog.setPayType(4);
            userMoneyLog.setStuats(1);
            boolean save = userMoneyLogService.save(userMoneyLog);
            if (!save){
                log.error("金额日志更新错误",userMoneyLog);
            }
        }

        UserMoneyLog userMoneyLog=new UserMoneyLog();
        userMoneyLog.setUserid(userid);
        userMoneyLog.setRemark("(建仓收益)订单编号:"+sysBuilding.getOrdinal());
        userMoneyLog.setCreateTime(new Date());
        userMoneyLog.setMoney(sysBuilding.getPrice()+sysBuilding.getPrice()*sysBuilding.getEarnings()/100);
        userMoneyLog.setPayType(1);
        userMoneyLog.setStuats(1);
        boolean save = userMoneyLogService.save(userMoneyLog);
        if (!save){
            log.error("金额日志更新错误",userMoneyLog);
        }
        long version6 = userMoney.getVersion();
        userMoney.setVersion(version6+1);
        boolean update2 = userMoneyService.update(userMoney, new QueryWrapper<UserMoney>().eq("id", userMoney.getId()).eq("version", version6));

        if (!update2){
            log.error("金额更新错误",userMoney);
        }
        groupHandler.resultHandler(sysBuilding);

    }

    @Transactional(rollbackFor = Exception.class)
    public void promotion(SysBuilding sysBuilding){
        //团队
        SysBuilding sysBuildinge=new SysBuilding();
        ToolUtil.copyProperties(sysBuilding,sysBuildinge);
        groupHandler.groupHandler(sysBuildinge);


        SysUserGroup group = sysUserGroupService.getOne(new QueryWrapper<SysUserGroup>().eq("userid", sysBuilding.getUserid()));
        Long referrerId = group.getReferrerId();
        UserMoney userMoney1 = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("userid", referrerId));
        if (userMoney1==null){
            log.error("没有一级用户" , userMoney1);
            return;
        }
        SysRebateSetting sysRebateSetting = sysRebateSettingService.getOne(null);

        SysBuilding sysBuilding1 = sysBuildingService.getOne(new QueryWrapper<SysBuilding>().eq("userid", userMoney1.getUserid())
                .eq("stuats", "1"));

        if (sysBuilding1!=null){
            long price=sysBuilding.getPrice();
            if (sysBuilding1.getType()<sysBuilding.getType()){
                ContractSetting contractSetting = contractSettingService.getOne(new QueryWrapper<ContractSetting>().eq("contract_type", sysBuilding1.getType()));
                price = contractSetting.getPrice1();
            }
            Long buyingDirect = sysRebateSetting.getBuyingDirect();
            Long rebateMoney = userMoney1.getRebateMoney();
            long sum=rebateMoney+price*sysBuilding.getEarnings()*buyingDirect/10000;
            userMoney1.setRebateMoney(sum);
            Long version = userMoney1.getVersion();
            userMoney1.setVersion(version+1);
            boolean update = userMoneyService.update(userMoney1, new QueryWrapper<UserMoney>().eq("id", userMoney1.getId()).eq("version", version));
            if (!update){
                log.error("一级推销金额更新错误",userMoney1);
                return;
            }
            SysRebate sysRebate=new SysRebate();
            sysRebate.setUserid(userMoney1.getUserid());
            sysRebate.setCreateTime(new Date());
            sysRebate.setOrdinal(sysBuilding.getOrdinal());
            sysRebate.setRebateType(2);
            sysRebate.setAppealRemark("一级直推建仓返利");
            sysRebate.setMoney(price*sysBuilding.getEarnings()*buyingDirect/10000);
            boolean save1 = sysRebateService.save(sysRebate);
            if (!save1){
                log.error("一级推销金额日志更新错误",sysRebate);
                return;
            }

        }

        Long sjReferrerId = group.getSjReferrerId();
        UserMoney userMoney2 = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("userid", sjReferrerId));
        if (userMoney2==null){
            log.error("没有二级用户" , userMoney2);
            return;
        }
        SysBuilding sysBuilding2 = sysBuildingService.getOne(new QueryWrapper<SysBuilding>().eq("userid", userMoney2.getUserid())
                .eq("stuats", "1"));

        if (sysBuilding2!=null){
            long price=sysBuilding.getPrice();
            if (sysBuilding2.getType()<sysBuilding.getType()){
                ContractSetting contractSetting = contractSettingService.getOne(new QueryWrapper<ContractSetting>().eq("contract_type", sysBuilding2.getType()));
                price = contractSetting.getPrice1();
            }
            Long buyingBetween = sysRebateSetting.getBuyingBetween();
            Long rebateMoney1= userMoney2.getRebateMoney();
            long sum1=rebateMoney1+price*sysBuilding.getEarnings()*buyingBetween/10000;
            userMoney2.setRebateMoney(sum1);
            Long version1 = userMoney2.getVersion();
            userMoney2.setVersion(version1+1);
            boolean update1 = userMoneyService.update(userMoney2, new QueryWrapper<UserMoney>().eq("id", userMoney2.getId()).eq("version", version1));
            if (!update1){
                log.error("二级推销金额更新错误",userMoney2);
                return;
            }
            SysRebate sysRebate1=new SysRebate();
            sysRebate1.setUserid(userMoney2.getUserid());
            sysRebate1.setCreateTime(new Date());
            sysRebate1.setOrdinal(sysBuilding.getOrdinal());
            sysRebate1.setRebateType(3);
            sysRebate1.setAppealRemark("二级间推建仓返利");
            sysRebate1.setMoney(price*sysBuilding.getEarnings()*buyingBetween/10000);
            boolean save2 = sysRebateService.save(sysRebate1);
            if (!save2){
                log.error("二级推销金额日志更新错误",sysRebate1);
                return;
            }
        }



    }
    @Transactional(rollbackFor = Exception.class)
    public  void buildingHandler1(SysBuilding sysBuilding) {
        String stuats = sysBuilding.getStuats();
        if ("2".equals(stuats)){
            log.error("建仓已完成",sysBuilding);
            return;
        }


      /*  sysBuilding.setStuats("2");
        sysBuilding.setMoney(sysBuilding.getPrice()*sysBuilding.getEarnings()/100);
        sysBuilding.setBuildingTime(new Date());
        int version5 = sysBuilding.getVersion();
        sysBuildingService.update(sysBuilding,new QueryWrapper<SysBuilding>().eq("id",sysBuilding.getId()).eq("version",version5));*/

        Long userid = sysBuilding.getUserid();
        UserMoney userMoney = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("userid", userid));
        userMoney.setAvailMoney(userMoney.getAvailMoney()+sysBuilding.getPrice()+(sysBuilding.getPrice()*sysBuilding.getEarnings()/100));
        if (userMoney.getFrozenCapital()==0){
            UserMoneySetting userMoneySetting = userMoneySettingService.getOne(null);
            userMoney.setFrozenCapital(userMoneySetting.getFrozenCapital());
            userMoney.setAvailMoney(userMoney.getAvailMoney()-userMoney.getFrozenCapital());
            userMoney.setBackup1(userMoneySetting.getFrozenDay());
            UserMoneyLog userMoneyLog=new UserMoneyLog();
            userMoneyLog.setUserid(userid);
            userMoneyLog.setRemark("冻结");
            userMoneyLog.setCreateTime(new Date());
            userMoneyLog.setMoney(userMoney.getFrozenCapital());
            userMoneyLog.setPayType(4);
            userMoneyLog.setStuats(1);
            boolean save = userMoneyLogService.save(userMoneyLog);
            if (!save){
                log.error("金额日志更新错误",userMoneyLog);
            }
        }

        UserMoneyLog userMoneyLog=new UserMoneyLog();
        userMoneyLog.setUserid(userid);
        userMoneyLog.setRemark("(建仓收益)订单编号:"+sysBuilding.getOrdinal());
        userMoneyLog.setCreateTime(new Date());
        userMoneyLog.setMoney(sysBuilding.getPrice()+sysBuilding.getPrice()*sysBuilding.getEarnings()/100);
        userMoneyLog.setPayType(1);
        userMoneyLog.setStuats(1);
        boolean save = userMoneyLogService.save(userMoneyLog);
        if (!save){
            log.error("金额日志更新错误",userMoneyLog);
        }
        long version6 = userMoney.getVersion();
        userMoney.setVersion(version6+1);
        boolean update2 = userMoneyService.update(userMoney, new QueryWrapper<UserMoney>().eq("id", userMoney.getId()).eq("version", version6));

        if (!update2){
            log.error("金额更新错误",userMoney);
        }

        groupHandler.resultHandler(sysBuilding);
    }

}
